package serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

import logic.SerialString;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class SimpleXMLSerializer<T> {
	
	
	private Serializer serializer;
	public SimpleXMLSerializer(){
		serializer = new Persister();

	}


	public byte[] serialize (Object source) throws Exception{
		//turns an object annotated with SimpleXML to a byte array 
	    ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
	    
	    File testFile = new File("broadcast.xml");
	    serializer.write(source, testFile);
	    serializer.write(source, bos);

	    // Get the bytes of the serialized object
	    byte[] bytes = bos.toByteArray();
	    
	    SerialString object = serializer.read(SerialString.class, testFile);
	    System.out.println(object.getString());
	    
		return bytes;
	}
	public T deserialize (Class<T> type,  byte[] source) throws Exception{
		//turns a flattened, SimpleXML object represented as bytes back into the object
		
	    // Deserialize from a byte array
		T object = serializer.read(type, (new ByteArrayInputStream(source)));
	    
		return object;
	}


}
